package com.huluobo.a2107jetpackkotlindemo.paging

import androidx.paging.PagingSource
import androidx.paging.PagingState
import java.lang.Exception

/**
 *  Created by LC on 2023/11/28.
 */
class RepoPagingSource(private val apiService: ApiService) : PagingSource<Int, GoodsBean>() {
    override fun getRefreshKey(state: PagingState<Int, GoodsBean>): Int? {
        return null
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, GoodsBean> {
        return try {
            val page = params.key ?: 1 //当前的页码
            val pageSize = params.loadSize//当前页面中item的数量
            val repo = apiService.queryData2(0, page, pageSize)//发起网络请求
            val repoItem = repo.data//请求返回的bean的集合,类似于adapter中的list,数据源
            val prevKey = if (page > 1) page - 1 else null //代表向前翻页的页码
            val nextKey = if (repoItem.isNotEmpty()) page + 1 else null//向后翻页的页码
            LoadResult.Page(repoItem, prevKey, nextKey)
        } catch (e: Exception) {
            LoadResult.Error(e)
        }
    }
}